import AsyncQueue from "@/model/AsyncQueue";
import errors from "./error";
import router from "@/router";
import { HIDE_ERROR_PROP } from "./request";
import { Message } from "element-ui";
import { delCookie, getObjMultiLevelValue } from "./tools";

// 默认后台返回接口指定的code和message
const DEFAULT_MESSAGE_PROP = {
	code: "result_code",
	message: "result_message",
};

// 获取请求地址
function getRequestUrl(response) {
	return response.config.url;
}

let loginExpiredTimer = null;
// 登陆过期删除缓存跳转登陆页
function loginExpired(response) {
	if (router && router.current && router.current.path === "/login") {
		return;
	}

	// 避免页面有多个请求异常后弹出一堆的登陆过期提示
	if (!loginExpiredTimer && !response.config[HIDE_ERROR_PROP]) {
		Message({
			message: errors["1001"],
			type: "error",
			center: true,
			duration: 2000,
		});

		loginExpiredTimer = setTimeout(() => {
			loginExpiredTimer = null;
		}, 1000);
	}

	localStorage.removeItem("userInfo");
	localStorage.removeItem("last_router");
	delCookie("UID_SAVE");
	delCookie("UID");
	router.history.push({
		path: "/login",
	});
}

/**
 * 指定后台返回接口指定的code和message对应的属性名称
 */
const RESPONSE_MESSAGE_PROP = {
	// 如果要添加特定对应接口或者接口前缀的过滤code，可参考:
	"/python.*": {
		code: "code",
		message: "message",
	},
};

const requestFilter = new AsyncQueue();

// 过滤后台返回内容
requestFilter.use(function (response, next) {
	const res = response.data;
	// 后台可能返回一个空字符串
	if (res) {
		next(Object.prototype.toString.call(res) !== "[object Object]");
	} else {
		if (res === false) {
			loginExpired(response);
		}
		next(true);
	}
});

// 单独针对登录接口，返回为true的情况处理
// requestFilter.use(function (response, next) {
//   next(response.data === true)
// })

// 取出后台返回的message和code
requestFilter.use(function (response, next) {
	const res = response.data;
	const requestUrl = getRequestUrl(response);
	let props = DEFAULT_MESSAGE_PROP;
	for (const key in RESPONSE_MESSAGE_PROP) {
		if (new RegExp(key).test(requestUrl)) {
			props = RESPONSE_MESSAGE_PROP[key];
		}
	}
	response.code = getObjMultiLevelValue(res, props.code);
	response.message = getObjMultiLevelValue(res, props.message);

	next();
});

// 状态码处理
requestFilter.use(function (response, next) {
	const code = Number(response.code);
	let message = response.message;
	if (code === 0 || code === "0" || code === 200 || code === "200") {
		return next();
	}
	response.error = new Error(message);

	next(true);
});

export default requestFilter;
